package com.guochenglang.www.service.impl;

import com.guochenglang.www.dao.ArticleDao;
import com.guochenglang.www.dao.BaseDao;
import com.guochenglang.www.dao.UserDao;
import com.guochenglang.www.pojo.Article;
import com.guochenglang.www.pojo.Base;
import com.guochenglang.www.pojo.User;
import com.guochenglang.www.service.SearchService;
import com.guochenglang.www.util.MyDependency;

import java.sql.SQLException;
import java.util.ArrayList;

/**
 * 搜索业务
 *
 * @author GuoChenglang
 */
public class SearchServiceImpl implements SearchService {
    /**
     * 关键词搜索用户
     *
     * @param keyword 输入框内容
     * @return 搜索的用户
     */
    @Override
    public ArrayList<User> userSearch(String keyword) {
        ArrayList<User> users = new ArrayList<>();
        try {
            //获得所有用户
            users = MyDependency.returnObject(UserDao.class).userSelect(new User());
        } catch (SQLException | IllegalAccessException | InstantiationException | InterruptedException e) {
            throw new RuntimeException(e);
        }
        ArrayList<User> selectedUsers = new ArrayList<>();
        //查看用户是否符合关键词
        for (User user : users) {
            if (user.getUsername().contains(keyword)) {
                selectedUsers.add(user);
            }
        }
        return selectedUsers;
    }

    /**
     * 关键词搜索知识库
     *
     * @param keyword 输入框内容
     * @return 搜索的知识库
     */
    @Override
    public ArrayList<Base> baseSearch(String keyword) {
        ArrayList<Base> bases = new ArrayList<>();
        //获得所有知识库
        try {
            bases = MyDependency.returnObject(BaseDao.class).baseSelect(new Base());
        } catch (SQLException | IllegalAccessException | InstantiationException | InterruptedException e) {
            throw new RuntimeException(e);
        }
        //判断知识库是否含有关键词
        ArrayList<Base> selectedBases = new ArrayList<>();
        for (Base basis : bases) {
            if (basis.getName().contains(keyword)) {
                selectedBases.add(basis);
            }
        }
        System.out.println(selectedBases);
        return selectedBases;
    }


    /**
     * 关键词搜索文章
     *
     * @param keyword 输入框内容
     * @return 搜索的文章
     */
    @Override
    public ArrayList<Article> articleSearch(String keyword) {
        ArrayList<Article> articles = new ArrayList<>();
        try {
            //获得所有文章
            articles = MyDependency.returnObject(ArticleDao.class).articleSelect(new Article());
        } catch (SQLException | IllegalAccessException | InstantiationException | InterruptedException e) {
            throw new RuntimeException(e);
        }
        //判断文章是否符合关键词
        ArrayList<Article> selectedArticles = new ArrayList<>();
        for (Article article : articles) {
            if (article.getTitle().contains(keyword)) {
                selectedArticles.add(article);
            }
        }
        return selectedArticles;
    }
}
